package cn.iune.platform.portal;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Transactional
@Service
public class ArticleNewsServiceImpl implements IArticleNewsService {

	@Autowired
	private IArticleNewsDao dao;
	
	public ArticleNewsServiceImpl(){

	}
	/* (non-Javadoc)
	 * @see com.iune.erp.plan.IArticleNewsService#getAll()
	 */
	@Override
	public List<ArticleNews> getAll(){
		return dao.getAll();
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.plan.IArticleNewsService#getByID(java.lang.String)
	 */
	@Override
	public ArticleNews getByID(String fID) {
		return dao.getByID(fID);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.plan.IArticleNewsService#insert(com.iune.erp.plan.ArticleNews)
	 */
	@Transactional
	@Override
	public void insert(ArticleNews obj){
		dao.insert(obj);
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.plan.IArticleNewsService#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.plan.IArticleNewsService#update(com.iune.erp.plan.ArticleNews)
	 */
	@Transactional
	@Override
	public void update(ArticleNews obj){
		dao.update(obj);
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.plan.IArticleNewsService#save(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		Table table= Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
				
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			ArticleNews obj = JSON.toJavaObject(javaObject, ArticleNews.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				ArticleNews objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("code", 0);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}

	@Override
	public JSONObject newData(JSONObject param) {
		return dao.create(param);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		//System.out.println("fileFactoryCreate.param-->>"+param.toJSONString());
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	/*
	在@Transaction注解中定义noRollbackFor和RollbackFor指定某种异常是否回滚。 
	@Transactional(noRollbackFor=RuntimeException.class) 
	@Transactional(RollbackFor=Exception.class) 
	*/
	@Transactional
	@Override
	public JSONObject saveData(JSONObject param) {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		JSONObject data;
		try {
			data = this.save(param);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#queryJDBC(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public JSONObject queryData(JSONObject param){
		//在此层面（ServiceImpl）统一处理异常，此层面直接被controller调用，面对BizData
		
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}

	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void createHtml(String id) {
		// TODO Auto-generated method stub
		
		
		//模板路径
		String templateDir = "/usr/local/nginx/html/news/articleNews/tpl";
		//生成文件存放路径
		String targetDir = "/usr/local/nginx/html/news/articleNews";
		
        String fileName = id+".html";
		
		try {  
            //创建一个合适的Configration对象  
            Configuration configuration = new Configuration(Configuration.getVersion());  
            configuration.setDirectoryForTemplateLoading(new File(templateDir));  
//            configuration.setObjectWrapper(new DefaultObjectWrapper());  
            configuration.setDefaultEncoding("UTF-8");   //这个一定要设置，不然在生成的页面中 会乱码  
            //获取或创建一个模版。  
            Template template = configuration.getTemplate("articleNews_tpl.html");  
            Map<String, Object> paramMap = new HashMap<String, Object>();  
            /*
            paramMap.put("description", "我正在学习使用Freemarker生成静态文件！");  
              
            List<String> nameList = new ArrayList<String>();  
            nameList.add("陈靖仇");  
            nameList.add("玉儿");  
            nameList.add("宇文拓");  
            paramMap.put("nameList", nameList);  
              
            Map<String, Object> weaponMap = new HashMap<String, Object>();  
            weaponMap.put("first", "轩辕剑");  
            weaponMap.put("second", "崆峒印");  
            weaponMap.put("third", "女娲石");  
            weaponMap.put("fourth", "神农鼎");  
            weaponMap.put("fifth", "伏羲琴");  
            weaponMap.put("sixth", "昆仑镜");  
            weaponMap.put("seventh", null);  
            paramMap.put("weaponMap", weaponMap);  
            */
            
            ArticleNews obj = this.getByID(id);
            
//            String cDatetime = obj.getcDatetime().toString();
//            paramMap.put("cDatetime", cDatetime);
//            String sAuthor = obj.getsAuthor();
//            paramMap.put("sAuthor", sAuthor);
            String originalName = obj.getOriginalName();
            paramMap.put("originalName", originalName);
          
            String sTitle = obj.getsTitle();
            paramMap.put("sTitle", sTitle);
            String sKeyWords = obj.getsKeyWords();
            paramMap.put("sKeyWords", sKeyWords);
            String summary = obj.getSummary();
            paramMap.put("summary", summary);
            String description = obj.getsDescription();
            paramMap.put("description", description);
            
            Writer writer  = new OutputStreamWriter(new FileOutputStream(targetDir+"//"+fileName),"UTF-8");  
            template.process(paramMap, writer);  
              
            System.out.println("恭喜，生成成功~~");  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
		catch (TemplateException e) {  
            e.printStackTrace();  
        }  
		
	}

}